package com.xxx.system.service.impl;


import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.base.exception.BusinessException;
import com.xxx.system.domain.Logininfo;
import com.xxx.system.domain.Menu;
import com.xxx.system.dto.LoginDTO;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import com.xxx.system.mapper.LogininfoMapper;
import com.xxx.system.mapper.MenuMapper;
import com.xxx.system.mapper.PermissionMapper;
import com.xxx.system.query.LogininfoQuery;
import com.xxx.system.service.ILogininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务实现类: 登录信息Logininfo
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LogininfoServiceImpl implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Logininfo> findAll() {
        return logininfoMapper.findAll();
    }

    @Override
    public Logininfo findOne(Long id) {
        return logininfoMapper.findOne(id);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //删除角色
        logininfoMapper.delete(id);
    }

    @Override
    @Transactional
    public void add(Logininfo logininfo) {
        //添加角色信息
        logininfoMapper.add(logininfo); //自增id
    }

    @Override
    @Transactional
    public void update(Logininfo logininfo) {
        logininfoMapper.update(logininfo);
    }

    @Override
    public void patchDelete(Long[] ids) {
        logininfoMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Logininfo> queryPage(LogininfoQuery logininfoQuery) {
        //1.开启分页
        PageHelper.startPage(logininfoQuery.getCurrentPage(), logininfoQuery.getPageSize());
        //a.查询总数量 - count()
        //b.会根据方言 mysql 自动实现分页查询,如果是mysql就会使用limit查询
        //c.自动计算limit的第一个参数: (currentPage-1)*pageSize
        //2.操作数据库
        List<Logininfo> data = logininfoMapper.queryPage(logininfoQuery);
        return new PageInfo<>(data);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        Logininfo logininfo = logininfoMapper.findByUserNameAndType(loginDTO);
        if (logininfo==null) {
           throw new BusinessException("用户名不存在");
        }
        //获取输入密码
        String InpPass = loginDTO.getPassword();
        //获取用户盐值
        String salt = logininfo.getSalt();
        String passFromUser = SecureUtil.md5(InpPass + salt);
        if (!passFromUser.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        //查询权限信息
        List<String> perms=permissionMapper.findpermsByLongininfoId(logininfo.getId());
        //参训菜单信息
        List<Menu> menus=menuMapper.findmenusByLongininfoId(logininfo.getId());
        //将菜单转换为菜单数,好让前端解析
        List<Menu> menuTree = getMenuTree(menus);

        Payload payload=new Payload();
        payload.setPermissions(perms);
        payload.setMenus(menuTree);
        //对敏感数据脱敏
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        payload.setLogininfo(logininfo);

        String jwt = JwtUtil.generateToken(payload);
        return jwt;

    }

    private List<Menu> getMenuTree(List<Menu> list) {

        //2.把所有list转换为map,id为key,自己为value
        Map<Long, Menu> menuMap =
                list.stream().collect(
                        Collectors.toMap(Menu::getId, (d) -> d)
                );
        //3.定义返回的typeTree集合
        List<Menu> typeTree = new ArrayList<Menu>();
        //4.找到顶层类型，没有上级类型就是顶级类型
        for (Menu menu : list) {
            if (menu.getParentId() == null) {
                typeTree.add(menu);
            } else {//非顶级类型加入到父级类型下
                //找到父类型
                Menu parentMenu = menuMap.get(menu.getParentId());
                //添加自己到父类型的子类型集合中
                parentMenu.getChildren().add(menu);
            }
        }
        return typeTree;
    }
}
